﻿using FanaticGene.AvaloniaMaid.Core.Properties;
using System;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;

namespace FanaticGene.AvaloniaMaid.Core
{

    public class AvaloniaArchive
    {
        #region props

        ///<summary>文档路径。</summary>
        public string ArchivePath { get; }

        public ControlThemeCollection ControlThemes { get; } = new ControlThemeCollection();

        #endregion

        #region ctors

        private AvaloniaArchive(string archivePath)
        {
            ArchivePath = archivePath;
        }

        #endregion


        #region statics

        ///<summary>导出文件夹。</summary>
        private static async Task ExtractArchiveAsync(string extraDir)
        {
            await Task.Run(() =>
            {
                var bytes = Resources.AvaloniaSrc;
                using var ms = new MemoryStream(bytes, false);
                using var zipArchive = new ZipArchive(ms);
                zipArchive.ExtractToDirectory(extraDir);
            });
        }
        private static void ExtractArchive(string extraDir)
        {
            var bytes = Resources.AvaloniaSrc;
            using var ms = new MemoryStream(bytes, false);
            using var zipArchive = new ZipArchive(ms);
            zipArchive.ExtractToDirectory(extraDir);
        }

        ///<summary>是否文件夹有内容。</summary>
        private static bool IsFolderHasContent(string archivePath)
        {
            if (string.IsNullOrWhiteSpace(archivePath)) return false;
            if (!Directory.Exists(archivePath)) return false;
            return Directory.GetDirectories(archivePath).Length > 0 || Directory.GetFiles(archivePath).Length > 0;

        }

        ///<summary>创建 Avalonia 文档文件。</summary>
        public static async Task<AvaloniaArchive> CreateAsync(string archivePath)
        {
            if (string.IsNullOrWhiteSpace(archivePath))
            {
                var rootBase = AppDomain.CurrentDomain.BaseDirectory;
                archivePath = Path.Combine(rootBase, "avasrc");
            }

            if (!IsFolderHasContent(archivePath))
                await ExtractArchiveAsync(archivePath);

            var archive = new AvaloniaArchive(archivePath); 
            var factory = new AvaloniaArchiveFactory();
            factory.LoadXamlFiles(archive);

            return archive;
        }

        public static AvaloniaArchive Create(string archivePath)
        {
            if (string.IsNullOrWhiteSpace(archivePath))
            {
                var rootBase = AppDomain.CurrentDomain.BaseDirectory;
                archivePath = Path.Combine(rootBase, "avasrc");
            }

            if (!IsFolderHasContent(archivePath))
                ExtractArchive(archivePath);

            var archive = new AvaloniaArchive(archivePath);
            var factory = new AvaloniaArchiveFactory();
            factory.LoadXamlFiles(archive);

            return archive;
        }

        #endregion

    }
}
